package com.yang.servlet;

import com.google.gson.Gson;
import com.yang.pojo.Menu2;
import com.yang.service.MenuService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;

@WebServlet("/Menu2ListByMenu1Servlet")
public class Menu2ListByMenu1Servlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        try {
            //接收到一级菜单的编号
            String parentCode = request.getParameter("parentCode");
//            System.out.println(parentCode);
            String parentCode1 = "0" + parentCode;
            //调用service的方法
            MenuService menuService = new MenuService();
            ArrayList<Menu2> menu2List = menuService.selectMnu2ByMenu1Code(parentCode1);
            //将menu2List的数据用json格式响应给页面
            Gson gson = new Gson();
            String jsonStr = gson.toJson(menu2List);

            response.setContentType("application/json;charset=utf-8");

            //在servlet中通过输出流响应ajax
            PrintWriter writer = response.getWriter();
            writer.println(jsonStr);
            writer.flush();
            writer.close();


        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
